<template>

    <el-button type="success" plain @click="AddRole()">新增</el-button>

    <!-- 表单 -->
    <div style="border-style:groove;border-width: 2px;margin-bottom: 20px;height: 550px;">
        <el-table :data="tableData" border style="width: 100%;height: 500px;">
            <el-table-column type="index" label="编号" width="55px" />
            <el-table-column prop="roleName" label="角色名称">
                <template v-slot="scoped">
                    <el-link @click="DelUserRole(scoped.row.id, scoped.row.roleName)">
                        {{ scoped.row.roleName }}
                    </el-link>
                </template>
            </el-table-column>

            <el-table-column prop="createUserName" label="创建人" width="100px" />
            <el-table-column prop="createTime" label="创建日期" width="170px">
                <template v-slot="scoped">
                    {{ moment(scoped.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
                </template>
            </el-table-column>
            <el-table-column prop="updateUserName" label="修改人" width="100px">
                <template v-slot="scoped">
                    {{ scoped.row.updateUserName == null ? "" : scoped.row.updateUserName }}
                </template>
            </el-table-column>
            <el-table-column prop="upDataTime" label="修改日期" width="170px">
                <template v-slot="scoped">
                    {{ scoped.row.upDataTime == null ? "" :
                        moment(scoped.row.upDataTime).format("YYYY-MM-DD HH:mm:ss") }}
                </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" width="300px">
                <template v-slot="scoped">
                    <el-button type="danger" plain @click="Del(scoped.row.id)">删除</el-button>
                    <el-button type="primary" plain @click="openUpdata(scoped.row)">修改</el-button>
                    <el-button type="success" plain @click="openRoleUser(scoped.row)">分配人员</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="demo-pagination-block">


            <el-pagination v-model:current-page="PageData.PageIndex" v-model:page-size="PageData.PageSize"
                :page-sizes="[15, 20, 25, 30]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="PageData.count" prev-text="上一页" next-text="下一页" />
        </div>
    </div>




    <!-- 新增 -->
    <el-dialog v-model="dialogFormVisible" title="新增" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="ruleForm.roleName" />
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog v-model="Update" title="修改" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="ruleForm.roleName" />
                </el-form-item>


                <el-form-item>
                    <el-button type="primary" @click="UpdatesubmitForm(ruleFormRef)">
                        保存
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </el-form>
    </el-dialog>

    <!--  角色分配人员 -->
    <el-dialog v-model="GiveRole" :title="'请设置【' + UserRoleLog.Titel + '】角色的员工'" width="500">
        <!-- <p style="">请设置</p><p style="color: red;">【{{ UserRoleLog.Titel }}】</p><p>角色的员工</p> -->

        <div class="common-layout">

            <el-container>
                <el-aside width="200px">
                    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules"
                        label-width="auto">



                        <el-tree ref="treeRef" style="max-width: 600px" class="filter-tree" :data="data"
                            :props="defaultProps" default-expand-all :filter-node-method="filterNode"
                            @node-click="GetUser" />


                    </el-form>
                </el-aside>
                <el-container>
                    <el-main>

                        <!--  <el-checkbox-group v-model="AddUserRole.userId">
                            <el-checkbox v-for="item in GiveDeptGetUserData" :value="item.id">
                                {{ item.userName }}
                            </el-checkbox>

                        </el-checkbox-group> -->


                        <el-tree ref="tree" style="max-width: 600px" :data="data1" show-checkbox node-key="id"
                            :props="defaultProps" :default-expand-all="true" v-model="AddUserRole.userId" />
                        <!-- <el-tree ref="treeRef" style="max-width: 600px" class="filter-tree" :data="data1"
                            :props="defaultProps" :filter-node-method="filterNode" /> -->


                    </el-main>
                    <el-footer>
                        <el-form-item>
                            <el-button type="primary" @click="GiveUserAddRole()">
                                保存
                            </el-button>
                        </el-form-item>
                    </el-footer>
                </el-container>
            </el-container>

        </div>


    </el-dialog>

    <!-- 查看角色对应的用户 -->
    <el-dialog v-model="OpenDelUserRole" title="" width="500" style="height: 400px;">

        <p style="display: grid;place-items: center;">属于角色【{{ UserRoleLog.RoleName }}】的员工如下：</p>
        <table>
            <tr v-for="item in AddUserRole.UserName">
                <td>{{ item.userName }}</td>
                <td @click="GiveRoleIdDelUser(item.id)">X</td>
            </tr>

            <tr>
                <td @click="openRoleUser1()">+</td>
            </tr>
        </table>

        <!-- <el-text v-for="item in AddUserRole.UserName" class="mx-1">{{ item }}</el-text> -->

    </el-dialog>



</template>

<script lang="ts" setup>
import axios from 'axios';
import { readB } from '@/http/axiosHelper'
import { onMounted, ref, watch, reactive } from 'vue';
import moment from 'moment';

const dialogFormVisible = ref(false)
const Update = ref(false)
const GiveRole = ref(false)
const OpenDelUserRole = ref(false)

const formLabelWidth = '140px'

const tableData = ref([]);
const PageData = ref({
    PageIndex: 1,
    PageSize: 15,
    count: 0,
})



//获取角色表单
const ShowRole = () => {
    readB.get("/api/Management/QueryRole", {
        params: {
            PageIndex: PageData.value.PageIndex,
            PageSize: PageData.value.PageSize
        }
    })
        .then(res => {
            if (res.data.code == 200) {
                tableData.value = res.data.pageData;
                PageData.value.count = res.data.count;

            }
        })
}

//修改按钮 弹出对话框
const openUpdata = async (row: any) => {
    Object.assign(ruleForm, row);

    Update.value = true;
}


//-----添加

import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { dataType } from 'element-plus/es/components/table-v2/src/common.mjs';


//添加角色按钮 弹出对话框
const AddRole = () => {
    ruleForm.roleName = "";
    dialogFormVisible.value = true;

}



const ruleFormRef = ref<FormInstance>()
//角色对象
const ruleForm = reactive({
    "id": 0,
    "roleName": "",
    "userId": localStorage.getItem("id")
})





const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
    roleName: [
        { required: true, message: '角色名称不能为空', trigger: 'blur' },

    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(ruleForm);

            readB.post("/api/Management/AddRole", ruleForm)
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.msg);
                        dialogFormVisible.value = false
                        ShowRole();
                    }
                    else {
                        ElMessage.error(res.data.msg);
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const UpdatesubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(ruleForm);

            readB.post("/api/Management/UpRoel", ruleForm)
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.msg);
                        Update.value = false
                        ShowRole();

                    }
                    else {
                        ElMessage.error(res.data.msg);
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))






onMounted(() => {
    ShowRole();

})

watch(() => { PageData.value.PageIndex, PageData.value.PageSize }, () => {
    ShowRole();
}, {
    deep: true
})




//删除角色
import { ElMessageBox } from 'element-plus'
const Del = (id: any) => {
    ElMessageBox.confirm(
        '确认删除么?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            readB.post("/api/Management/DelRole", null, {
                params: {
                    Id: id
                }
            })
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.msg);
                        ShowRole();
                    }
                    else {
                        ElMessage.error(res.data.msg);
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

const UserRoleLog = ref({
    Titel: "",
    RoleName: "",
    DeptId: 0
})

//分配人员 打开对话框
const openRoleUser = (row: any) => {
    UserRoleLog.value.Titel = row.roleName;
    //显示用户
    GiveDeptGetUser(1);

    AddUserRole.value.roleId = row.id

    GiveRoleGetUserId();
    //反填数据
    GiveRole.value = true;
}



//-----------------树形
import type { ElTree, FilterNodeMethodFunction, TreeInstance } from 'element-plus'
import { id } from 'element-plus/es/locales.mjs';

interface Tree {
    [key: string]: any
}

const filterText = ref('')
const treeRef = ref<TreeInstance>()

const defaultProps = {
    children: 'children',
    label: 'label',
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})
/* 
const filterNode: FilterNodeMethodFunction = (value: string, data: Tree) => { */
const filterNode: any = (value: string, data: Tree) => {
    if (!value) return true
    return data.label.includes(value)
}

const data: Tree[] = [
    {
        label: '选择部门',
        children: [
            {
                id: 1,
                label: 'IT信息部',
            },
            {
                id: 2,
                label: '人力资源部',
            },
            {
                id: 3,
                label: '财务部',
            },

            {
                id: 4,
                label: '销售部',
            },
            {
                id: 5,
                label: '行政部',
            }
        ],
    },

]


//树形node-click 点击事件 根据 部门Id 获取用户 
const GetUser = (data: any) => {
    AddUserRole.value.deptId = data.id
    GiveDeptGetUser(data.id)

}

//用户对象
const GiveDeptGetUserData = ref([{
    id: 0,
    userName: ""
}])

//根据 部门Id 获取用户 
const GiveDeptGetUser = (id: any) => {
    readB.get("/api/Management/GiveDeptGetUser", {
        params: {
            DeptId: id
        }
    })
        .then(res => {
            GiveDeptGetUserData.value = res.data.data

            let list = res.data.data;



            data1.value = [
                {
                    ...data1.value[0],
                    children: list.map((user: any) => ({
                        id: user.id,
                        label: user.userName

                    }))
                }
            ];

        })
}


//角色分配用户
const AddUserRole = ref({
    roleId: 0,
    userId: "",
    createId: localStorage.getItem("id"),
    deptId: 0,
    UserName: [{
        "id": 0,
        "userName": ""
    }]
});

//分配用户角色
const GiveUserAddRole = () => {


    const perId = tree.value?.getCheckedKeys(false) || [];
    AddUserRole.value.userId = perId.toString();


    console.log(perId);
    readB.post("/api/Management/UserGiveRole", AddUserRole.value)
        .then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.msg);
                GiveRole.value = false;
                GiveRoleGetUserId();

            }
            else {
                ElMessage.error(res.data.msg);
            }
        })
}

const tree = ref<InstanceType<typeof ElTree>>();

//通过角色id 获取用户所用信息
const GiveRoleGetUserId = () => {


    readB.get("/api/Management/GetUserId", {
        params: {
            RoleId: AddUserRole.value.roleId

        }
    })
        .then(res => {
            console.log(res.data.data);

            let list = res.data.data.map((item: any) => Number(item.id))
            tree.value?.setCheckedKeys(list, true);
            AddUserRole.value.UserName = res.data.data
        })
}


//
const DelUserRole = (id: any, name: string) => {
    UserRoleLog.value.Titel = name;
    UserRoleLog.value.RoleName = name
    AddUserRole.value.roleId = id
    GiveRoleGetUserId();
    OpenDelUserRole.value = true;
}

//+
const openRoleUser1 = () => {

    //显示用户
    GiveDeptGetUser(1);
    GiveRoleGetUserId();
    //反填数据
    GiveRole.value = true;
}

//删除 用户角色关系
const GiveRoleIdDelUser = (id: any) => {
    ElMessageBox.confirm(
        '确认删除么?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            readB.post("/api/Management/DelUserRole", null, {
                params: {
                    UserId: id,
                    RoleId: AddUserRole.value.roleId
                }
            })
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.msg);
                        GiveRoleGetUserId();
                    }
                    else {
                        ElMessage.error(res.data.msg);
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}



//树
interface Tree {
    label: string
    children?: Tree[]
}

//将 对象 变成 树形类型
const data1 = ref<Tree[]>([
    {
        id: 0,
        label: '请选择用户',
        children: []
    }
]);



</script>
